/*
__token => session => initiaUserInfo  | getUserInfo Api https://fxg.jinritemai.com/ffa/g/create  | Window.defaultData
_lid: String(Date.now()).substr(5) + String(Math.random()).substr(2, 4)
_bid: 固定的值 不同接口不同的值
msToken => cookie
*/
import { getOssKeyApi } from '@Api/toolsApi'
import moment from 'moment'
// import OSS from 'ali-oss'
/**
 * 
 * @param {string} key CookieName
 * @returns 获取Cookie
 */
export const getCookie = (key) => {
  const cookieList = document.cookie.split("; ").map((res) => {
    let ck = res.split("=")
    return {
      name: ck[0],
      val: ck[1]
    }
  })
  const getfilter = cookieList.filter((ckl) => {
    return ckl.name === key
  })
  if (getfilter && getfilter.length) {
    return getfilter[0].val
  }
  return ''
}
/**
 * 
 * @returns 获取参数 _lid 生成不同的数字字符串
 */
export const get_lid = () => {
  return String(Date.now()).substr(5) + String(Math.random()).substr(2, 4)
}

/**
 * 
 * @returns 获取__token
 * @return {
 *  userInfo: object ,
 *  __token: string
 * }
 */
export const get__token = () => {
  const sessionUserInfo = sessionStorage.getItem('initialUserInfo')
  const userInfo = JSON.parse(sessionUserInfo).data
  return {
    userInfo,
    __token: userInfo && userInfo.token
  }
}
export const getOssKeyData = async () => {
  const wtOssKey = localStorage.getItem('wtOssKey')
  try {
    if (wtOssKey) {
      const ossKey = JSON.parse(wtOssKey)
      if (moment().add(10, 'minutes').isBefore(moment(new Date(ossKey.Expiration)))) {
        return JSON.parse(wtOssKey)
      }
    }

    const ossKey = await getOssKeyApi()

    localStorage.setItem('wtOssKey', JSON.stringify(ossKey))
    return ossKey
  } catch (error) {
    const ossKey = await getOssKeyApi()
    localStorage.setItem('wtOssKey', JSON.stringify(ossKey))
    return ossKey
  }
}
/**
 *
 * @param {
 * fileName: 文件名
 * file: 文件
 * bucke: '',
 * region
 * } file
 */
// export const upFileToOss = async (file) => {
//   const ossKey = await getOssKeyData()
// //   REGION = oss-cn-hangzhou
// // BUCKER = wtplug
//   const client = new OSS({
//     accessKeyId: ossKey.AccessKeyId,
//     accessKeySecret: ossKey.AccessKeySecret,
//     stsToken: ossKey.SecurityToken,
//     region: file.region || process.env.PLASMO_PUBLIC_REGION || 'oss-cn-hangzhou',
//     bucket: file.bucket || process.env.PLASMO_PUBLIC_BUCKER || 'wtplug',
//     // secure: true, 
//   })
//   const fileName = 'shopImage/'+file.fileName
//   const filea = file.file
//   if(!fileName || !filea ) {
//     throw new Error("文件名和文件不能同时为空")
//   }
//   const result = await client.put(fileName, filea,{
//     timeout: 60000000
//   })
//   return  result

// }